<template>
  <div class="app-container">
    <el-form ref="incubatorForm" :model="incubatorForm" :rules="incubatorFormRule" label-width="120px" class="form-container">
      <el-row>
        <el-col :span="8" :offset="8">
          <el-form-item label-width="0" prop="name">
            <el-input v-model="incubatorForm.name" placeholder="请输入保温箱名称"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-card>
        <el-form-item>
          <div class="el-card_tit">
            <span>基本信息</span>
          </div>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌：" prop="brand">
              <el-input v-model="incubatorForm.brand"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号：" prop="model">
              <el-input v-model="incubatorForm.model"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="客户编号：" prop="customerCode">
              <el-tooltip class="item" effect="dark" content="客户名称首字母大写，7位，不足7位补0；如（SYCZYY0）" placement="top-end">
                <el-input v-model="incubatorForm.customerCode"/>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="验证编号：" prop="factoryCode">
              <el-tooltip class="item" effect="dark" content="DP-客户编号（7位）-（X:保温箱,K:库房,C:冷藏车,G:冰柜,S:系统）-编号；如：DP-SYCZYY0-X-001" placement="top-end">
                <el-input v-model="incubatorForm.factoryCode"/>
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="隔离措施：" prop="measure">
          <el-input v-model="incubatorForm.measure"/>
        </el-form-item>

        <el-form-item>
          <div class="el-card_tit">
            <span>技术参数</span>
          </div>
        </el-form-item>

        <el-form-item label="外部尺寸长：">
          <span>
            <el-input-number v-model="incubatorForm.outlength" :min="0" label="长"/>&nbsp;mm，
          </span>
          <span>
            <span>宽：</span>
            <el-input-number v-model="incubatorForm.outwidth" :min="0" label="宽"/>&nbsp;mm，
          </span>
          <span>
            <span>高：</span>
            <el-input-number v-model="incubatorForm.outheight" :min="0" label="高"/>&nbsp;mm
          </span>
        </el-form-item>

        <el-form-item label="内部尺寸长：">
          <span>
            <el-input-number v-model="incubatorForm.inlength" :min="0" label="长" @change="UpdateVolume"/>&nbsp;mm，
          </span>
          <span>
            <span>宽：</span>
            <el-input-number v-model="incubatorForm.inwidth" :min="0" label="宽" @change="UpdateVolume"/>&nbsp;mm，
          </span>
          <span>
            <span>高：</span>
            <el-input-number v-model="incubatorForm.inheight" :min="0" label="高" @change="UpdateVolume"/>&nbsp;mm
          </span>
        </el-form-item>
        <el-form-item label="保温箱容积：">
          <el-input-number v-model="incubatorForm.volume" :precision="2" :min="0" label="容积"/>&nbsp;L，
        </el-form-item>

        <el-form-item label="保温层材料：" prop="material">
          <el-input v-model="incubatorForm.material"/>
        </el-form-item>

        <el-form-item>
          <div class="el-card_tit">
            <span>配送测温仪</span>
          </div>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌：" prop="thermometerBrand">
              <el-input v-model="incubatorForm.thermometerBrand"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量：">
              <el-input-number v-model="incubatorForm.thermometerCount" :min="0" label="数量"/>&nbsp;个
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-show="!isEdit">
          <div class="el-card_tit">
            <span>保温箱图片</span>
          </div>
        </el-form-item>
        <!-- <UploadImg :picList="incubatorForm.picList" :picDel="picDel" :handleChange="handleChange" :Data="incubatorData" :FileUrl="incubatorFileUrl" ref="eluploadincubatorimg"></UploadImg> -->
        <el-form-item v-show="!isEdit" label="保温箱图片：" prop="picList">
          <el-upload
            :action="incubatorFileUrl"
            ref="eluploadincubatorimg"
            multiple
            :data="incubatorData"
            list-type="picture-card"
            :auto-upload="false"
            :headers="httpHeaders"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :file-list="incubatorForm.picList"
            :on-change="handleChange"
            :on-success="handleSuccess"
            :on-progress="handleProgress"
          >
            <i class="el-icon-plus"/>
            <div slot="tip" class="el-upload__tip">
              <p>只能上传jpg/png文件</p>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item v-show="!isEdit">
          <div class="el-card_tit">
            <span>蓄冷剂配置</span>
            <el-button style="margin-left:30px;" size="small" type="primary" @click="addRefrigerant()">新增蓄冷剂组</el-button>
          </div>
        </el-form-item>

        <el-form ref="refrigerantForm" v-show="!isEdit" :model="refrigerantForm" label-width="120px">
          <div v-for="(item,index) in refrigerantForm.refrigerantGroup" :key="index" class="refrigerantGroup clearfix">
            <el-row>
              <el-col :span="4">
                <el-form-item :prop="'refrigerantGroup.' + index +'.name'" :rules="refrigerantFormRule.name" label-width="0">
                  <el-input v-model="item.name" placeholder="请输入蓄冷剂组名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <el-form-item label="温度范围：">
                  <span>
                    <el-input-number v-model="item.lowTemperature" :precision="2" :step="0.1" label="最低温度："/>&nbsp;℃
                  </span>
                  <span>到</span>
                  <span>
                    <el-input-number v-model="item.highTempature" :precision="2" :step="0.1" label="最高温度："/>&nbsp;℃
                  </span>
                </el-form-item>
                <el-form-item label="蓄冷剂长：">
                  <span>
                    <el-input-number v-model="item.length" :min="0" label="长"/>，
                  </span>
                  <span>
                    <span>宽</span>
                    <el-input-number v-model="item.width" :min="0" label="宽"/>，
                  </span>
                  <span>
                    <span>高</span>
                    <el-input-number v-model="item.height" :min="0" label="高"/>&nbsp;(mm)
                  </span>
                </el-form-item>
              </el-col>

              <el-col :span="20" :offset="4">
                <el-form-item :prop="'refrigerantGroup.' + index +'.model'" :rules="refrigerantFormRule.model" label="蓄冷剂型号：">
                  <el-input v-model="item.model"/>
                </el-form-item>
                <el-form-item :prop="'refrigerantGroup.' + index +'.count'" label="蓄冷剂数量：">
                  <el-input-number v-model="item.count"/>个
                </el-form-item>
                <el-form-item label="变相温度">
                  <el-input-number v-model="item.temperature" :precision="2" label="变相温度"/>&nbsp;℃
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="16" :offset="4">
                <el-form-item :prop="'refrigerantGroup.' + index +'.picList'" :rules="refrigerantFormRule.picList" label="蓄冷剂图片：">
                  <el-upload
                    :ref="'eluploadrefrigerantimg'+index"
                    :action="refrigerantFileUrl"
                    :data="refrigerantData"
                    :auto-upload="false"
                    multiple 
                    :headers="httpHeaders" 
                    list-type="picture-card" 
                    :on-preview="handlePictureCardPreview"
                    :on-change="refrigerantimgChange"
                    :on-remove="handleRemove"
                    :file-list="item.picList"
                    :on-success="handleSuccess"
                    :on-progress="handleProgress"
                  >
                    <i class="el-icon-plus"/>
                    <div slot="tip" class="el-upload__tip">
                      <p>只能上传jpg/png文件</p>
                    </div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <el-form-item label="备注">
          <el-input v-model="incubatorForm.remark" type="textarea"/>
        </el-form-item>

        <div class="btnGroup">
          <el-button type="primary" @click="submitForm('incubatorForm')">提交</el-button>
          <el-button @click="resetForm('incubatorForm')">重置</el-button>
        </div>
        <el-dialog :visible.sync="dialogVisible">
          <img :src="dialogImageUrl" width="100%" alt>
        </el-dialog>
      </el-card>
    </el-form>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { mapGetters } from "vuex";
import UploadImg from "@/components/Upload/UploadImg";
import {
  getRefrigerantList,
  getIncubatorData,
  updateIncubator,
  createIncubator,
  createRefrigerant
} from "@/api/incubator";
const defaultIncubatorForm = {
  brand: "",
  customerCode: "",
  factoryCode: "",
  inheight: "",
  inlength: "",
  inwidth: "",
  material: "",
  measure: "",
  model: "",
  name: "",
  outheight: 0,
  outlength: 0,
  outwidth: 0,
  remarks: "",
  thermometerBrand: "",
  thermometerCount: "",
  volume: 0,
  picList: []
};

export default {
  name: "IncubatorDetail",
  components: { UploadImg },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    var refrigerantPicList = (rule, value, callback) => { // 图片验证
      if (this.hasImg == false) {
          callback(new Error('请上传蓄冷剂图片'));
      } else {
          callback();
      }
    }
    return {
      uploadCount: 0,
      listLoading: false,
      httpHeaders: {
        Authorization: getToken()
      },
      hasImg:false,
      incubatorData: {},
      refrigerantData: {},
      incubatorForm: Object.assign({}, defaultIncubatorForm),
      loading: false,
      incubatorFormRule: {
        brand: [
          {
            type: "string",
            required: true,
            message: "请输入保温箱品牌",
            trigger: "blur"
          }
        ],
        customerCode: [
          {
            type: "string",
            required: true,
            message: "请输入客户编号",
            trigger: "blur"
          }
        ],
        factoryCode: [
          {
            type: "string",
            required: true,
            message: "请输入验证编号",
            trigger: "blur"
          }
        ],
        model: [
          {
            type: "string",
            required: true,
            message: "请输入保温箱型号",
            trigger: "blur"
          }
        ],
        material: [
          {
            type: "string",
            required: true,
            message: "请输入保温层材料",
            trigger: "blur"
          }
        ],
        measure: [
          {
            type: "string",
            required: true,
            message: "请输入隔离措施",
            trigger: "blur"
          }
        ],
        name: [
          {
            type: "string",
            required: true,
            message: "请输入保温箱名称",
            trigger: "blur"
          }
        ],
        thermometerBrand: [
          {
            type: "string",
            required: true,
            message: "请输入测温仪品牌",
            trigger: "blur"
          }
        ],
        picList: [
          {
            required: true,
            type: "array",
            message: "请上传保温箱图片",
            trigger: "change"
          }
        ]
      },
      refrigerantForm: {
        refrigerantGroup: []
      },
      refrigerantFormRule: {
        name: [
          {
            type: "string",
            required: true,
            message: "请输入蓄冷剂组名称",
            trigger: "blur"
          }
        ],
        model: [
          {
            type: "string",
            required: true,
            message: "请输入蓄冷剂型号",
            trigger: "blur"
          }
        ],
        picList: [
           { required:true, validator: refrigerantPicList, trigger: 'change' } 
          // { required: true, message: "请上传蓄冷剂组图片", trigger: "change" }
        ]
      },
      refrigerantFileUrl: "http://gsp.coldcloud.com/refrigerant/pic/insert",
      incubatorFileUrl: "http://gsp.coldcloud.com/incubator/pic/insert",
      dialogImageUrl: "",
      dialogVisible: false
    };
  },
  watch: {
    incubatorForm: {
      handler(newval, oldval) {
        this.incubatorForm.picList = newval.picList;
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    ...mapGetters(["customerid"])
  },
  created() {
    if (this.isEdit) {
      this.IncubatorData();
    } else {
      this.incubatorForm = Object.assign({}, defaultIncubatorForm);
    }
  },

  methods: {
    handleProgress(event, file, fileList) {
      if (event.percent == 100) {
        this.uploadCount++;
      }
    },
    handleSuccess(file, fileList) {
      const that = this;
      setTimeout(function() {
        that.uploadCount--;
        if (that.uploadCount == 0) {
          that.$notify({
            title: "成功",
            message: "发布成功，您可以继续添加",
            type: "success",
            duration: 2000
          });
          that.incubatorForm.picList = [];
          that.refrigerantForm.refrigerantGroup.forEach(v => {
            v.picList = [];
          });
          // that.incubatorForm = Object.assign({}, defaultIncubatorForm);
          // that.$router.push({ path:'/devices/incubatorList'})
        }
      }, 500);
    },
    handleRemove(file, fileList) {},
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleChange(file, fileList) {
      const isImage =
        file.raw.type == "image/png" ||
        file.raw.type == "image/jpg" ||
        file.raw.type == "image/jpeg";
      if (!isImage) {
        this.$message.error("上传图片只能是JPG或者png格式!");
         fileList.pop();
      }else {
        this.incubatorForm.picList = fileList;
      } 
      return isImage;
    },
    refrigerantimgChange(file,fileList) {
    console.log(file,fileList)
      const isImage =
        file.raw.type == "image/png" ||
        file.raw.type == "image/jpg" ||
        file.raw.type == "image/jpeg";
      if (!isImage) {
        this.$message.error("上传图片只能是JPG或者png格式!");
         fileList.pop();
      }else {
        if(fileList.length > 0){
          this.hasImg = true;
        }

       // this.refrigerantForm.refrigerantGroup[index].picList = fileList;
        // let length = this.refrigerantForm.refrigerantGroup.length;
        // for( let i = 0;i<length;i++){ 
        //   console.log(this.refrigerantForm.refrigerantGroup[i].picList)
        // }   
      } 
      return isImage;
    },
    // 容积
    UpdateVolume() {
      this.incubatorForm.volume =
        (this.incubatorForm.inlength *
          this.incubatorForm.inwidth *
          this.incubatorForm.inheight) /
        1000 /
        1000;
    },

    // 新增蓄冷机组
    addRefrigerant() {
      this.refrigerantForm.refrigerantGroup.push({
        name: "",
        highTempature: 0,
        lowTemperature: 0,
        model: "",
        length: 0,
        width: 0,
        height: 0,
        temperature: 0,
        count: 0,
        picList: []
      });
    },
    // 获取表单信息
    IncubatorData() {
      this.listLoading = true;
      getIncubatorData({ incubatorId: this.$route.params.id })
        .then(response => {
          this.incubatorForm = response.data;
          getRefrigerantList({ incubatorId: this.$route.params.id }).then(
            response => {
              this.refrigerantForm.refrigerantGroup = response.data;
            }
          );
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 重置表单
    resetForm(incubatorForm, refrigerantForm) {
      const that = this;
      this.$refs["incubatorForm"].resetFields();
      this.$refs.eluploadincubatorimg.clearFiles();
      const length = this.refrigerantForm.refrigerantGroup.length;
      for (let i = 0; i < length; i++) {
        const refName = `eluploadrefrigerantimg${i}`;
        that.$refs[refName][0].clearFiles();
      }
    },

    submitForm(incubatorForm, refrigerantForm) {
      if (this.isEdit) {
        this.incubatorFormRule.picList = [];
      }
      if (this.refrigerantForm.refrigerantGroup.length < 1) {
        this.$message({
          message: "保温箱需配套至少一组蓄冷剂！",
          type: "warning"
        });
        return;
      }
      this.$refs["incubatorForm"].validate(valid => {
        if (valid) {
          this.$refs.refrigerantForm.validate(v => {
            if (v) {
              this.$confirm("确认提交吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消"
              }).then(() => {
                if (!this.isEdit) {
                  const tempData = {
                    customerId: this.customerid
                  };
                  Object.assign(tempData, this.incubatorForm);
                  createIncubator(tempData).then(res => {
                    const incubatorId = res.data.insertId;
                    this.incubatorData = { incubatorId: incubatorId };
                    const that = this;
                    const length = this.refrigerantForm.refrigerantGroup.length;
                    that.$nextTick(() => {
                      that.$refs.eluploadincubatorimg.submit();
                    });
                    for (let i = 0; i < length; i++) {
                      const data = Object.assign({}, that.refrigerantForm.refrigerantGroup[i], { incubatorId });
                      createRefrigerant(data).then(res => {
                        const refrigerantId = res.data.insertId;
                        that.refrigerantData = { refrigerantId: refrigerantId };
                        const refName = `eluploadrefrigerantimg${i}`;
                        this.$nextTick(() => {
                          if (this.$refs[refName] != undefined) {
                            this.$refs[refName][0].submit();
                          }
                        });
                      });
                    }
                  });
                } else {
                  if (this.isEdit) {
                    this.loading = true;
                    const tempData = Object.assign({}, this.incubatorForm);
                    updateIncubator(tempData).then(() => {
                      this.$notify({
                        title: "修改",
                        message: "修改成功",
                        type: "success",
                        duration: 2000
                      });
                      this.IncubatorData();
                      this.loading = false;
                    });
                  }
                }
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.refrigerantGroup {
  position: relative;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;

  .delbtn {
    position: absolute;
    bottom: 20px;
    right: 0;
  }
}
.btnGroup {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  text-align: center;
}
.picList {
  margin-bottom: 30px;
}
</style>

